<template>
  <div class="page-user-login">
    <van-nav-bar title="登录" />
    <van-form @submit="onSubmit">
      <van-field
        v-model="from.mobile"
        name="mobile"
        label="手机号"
        placeholder="手机号"
        :rules="[
          { required: true, message: '请填写手机号' },
          { pattern, message: '请输入正确格式手机号' },
        ]"
      />
      <van-field
        v-model="from.code"
        name="code"
        label="验证码"
        placeholder="验证码"
        :rules="[
          { required: true, message: '请填写验证码' },
          { validator, message: '请输入正确验证码' },
        ]"
      >
        <template #button>
          <van-button type="primary" size="small" native-type="button"
            >获取验证码</van-button
          >
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapActions } from 'vuex'
export default {
  data () {
    return {
      from: {
        mobile: '',
        code: '246810'
      },
      pattern: /^(0|86|17951)?(13[0-9]|15[012356789]|166|17[3678]|18[0-9]|14[57])[0-9]{8}$/
    }
  },
  methods: {
    ...mapActions(['getToken']),
    async onSubmit (values) {
      try {
        await this.getToken(values)
        this.$toast.success('登陆成功')
        this.$router.push(this.$route.query.redirectUrl || '/')
      } catch (error) {
        this.$toast.fail(error.message)
      }
    },
    validator (val) {
      if (val.length !== 6) {
        return false
      } else {
        return true
      }
    }
  }
}
</script>

<style lang="less" scoped>
</style>
